package com.ThreadTest.locks;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author YongQiang
 * @Date 2021/2/25 20:05
 * @Version 1.0
 */
public class CycliBarrierDemo {

    public static void main(String[] args) throws InterruptedException {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1启动");
                try {
                    cyclicBarrier.await();
                    System.out.println("线程1开始");
                    Thread.sleep(1000);
                    System.out.println("线程1结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程2启动");
                try {
                    cyclicBarrier.await();
                    System.out.println("线程2开始");
                    Thread.sleep(1000);
                    System.out.println("线程2结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程3启动");
                try {
                    cyclicBarrier.await();
                    System.out.println("线程3开始");
                    Thread.sleep(1000);
                    System.out.println("线程3结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        t2.start();
        Thread.sleep(1000);
        t3.start();

    }
}
